package com.pay.ioopos.fragment;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.pay.ioopos.R;
import com.pay.ioopos.support.utils.MacUtil;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

/**
 * 网络信息
 * @author    Moyq5
 * @since  2020/4/1 9:33
 */
public class NetInfoFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_net_info, container, false);
        TextView netView = view.findViewById(R.id.net);
        netView.setText(net());
        TextView macView = view.findViewById(R.id.mac);
        macView.setText(MacUtil.getMac(getContext()));
        String[] ips = ips();
        TextView ipView = view.findViewById(R.id.ip);
        ipView.setText(ips[0]);
        TextView maskView = view.findViewById(R.id.mask);
        maskView.setText(ips[1]);
        TextView dnsView = view.findViewById(R.id.dns);
        dnsView.setText(dns());
        return view;

    }

    /**
     * 获取网络类型
     * @author  Moyq5
     * @since    2020/4/1 15:18
     * @param
     * @return
     */
    private String net() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network = cm.getActiveNetwork();
        if (null == network) {
            return "网络未连";
        }
        NetworkCapabilities nc = cm.getNetworkCapabilities(network);
        if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
            return "网络未连";
        }
        String valid = "";
        if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            valid = "（不可上网）";
        }
        if (nc.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
            return "有线网络" + valid;
        }
        if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            return "WIFI网络" + valid;
        }
        if (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            return "移动网络" + valid;
        }
        return "未知";
    }

    /**
     * 获取ip和子网掩码
     * @author  Moyq5
     * @since    2020/4/1 15:17
     * @param
     * @return
     */
    private String[] ips() {
        String[] ips = new String[2];
        try{
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface ni;
            List<InterfaceAddress> ids;
            Iterator<InterfaceAddress> iid;
            InterfaceAddress id;
            InetAddress ia;
            String ip;
            while(interfaces.hasMoreElements()) {
                ni = interfaces.nextElement();
                if (!ni.isUp()) { // 判断网卡是否在使用
                    continue;
                }
                ids = ni.getInterfaceAddresses();
                iid = ids.iterator();
                while (iid.hasNext()) {
                    id = iid.next();
                    ia = id.getAddress();
                    if (ia.isLoopbackAddress()) {
                        continue;
                    }
                    ip = ia.getHostAddress();
                    if (ia.isSiteLocalAddress()) {
                        int index = ip.indexOf("%wlan0");
                        if (index != -1) {
                            ip = ip.substring(0, index);
                        }
                        ips[0] = ip;
                        ips[1] = calcMaskByPrefixLength(id.getNetworkPrefixLength());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ips;
    }

    /**
     * 获取dns
     * @author  Moyq5
     * @since    2020/4/1 15:18
     * @param
     * @return
     */
    private String dns() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network = cm.getActiveNetwork();
        if (null == network) {
            return "";
        }
        LinkProperties lp = cm.getLinkProperties(network);
        for (InetAddress ia : lp.getDnsServers()) {
            return ia.getHostAddress();
        }
        return "";
    }

    /**
     * 计算出子网掩码
     * @author  Moyq5
     * @since    2020/4/1 15:18
     * @param
     * @return
     */
    private static String calcMaskByPrefixLength(int length) {

        int mask = 0xffffffff << (32 - length);
        int partsNum = 4;
        int bitsOfPart = 8;
        int maskParts[] = new int[partsNum];
        int selector = 0x000000ff;

        for (int i = 0; i < maskParts.length; i++) {
            int pos = maskParts.length - 1 - i;
            maskParts[pos] = (mask >> (i * bitsOfPart)) & selector;
        }

        String result = "";
        result = result + maskParts[0];
        for (int i = 1; i < maskParts.length; i++) {
            result = result + "." + maskParts[i];
        }
        return result;
    }

}
